﻿using HandyControl.Controls;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Ping9719.WpfEx.Mvvm;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;

namespace BaseUi.ViewModels
{
    /// <summary>
    /// 设置组model。在界面上使用的时候再绑定设置DataContext属性【DataContext = new SetGroupViewModel<T>()】来完成绑定操作;
    /// </summary>
    public class SetGroupViewModel<T> : BindableBase where T : SetGroupBase, new()
    {
        private List<T> DataList_;
        /// <summary>
        /// 所有项
        /// </summary>
        public List<T> DataList { get => DataList_; set { value = value.OrderBy(o => o.Sort).ToList(); SetProperty(ref DataList_, value); } }

        private T DataSelect_;
        /// <summary>
        /// 选中的项
        /// </summary>
        public T DataSelect { get => DataSelect_; set { SetProperty(ref DataSelect_, value); SelectNoNull = value != null; if (value != null) DataList?.ForEach(o => o.IsSelect = false); if (value != null) value.IsSelect = true; } }

        private bool SelectNoNull_;
        public bool SelectNoNull { get => SelectNoNull_; set { SetProperty(ref SelectNoNull_, value); } }

        /// <summary>
        /// 深拷贝数据并导出数据
        /// </summary>
        /// <returns></returns>
        public List<T> GetData()
        {
            var values = DataList?.ToList() ?? new List<T>();
            return JsonConvert.DeserializeObject<List<T>>(JsonConvert.SerializeObject(values)) ?? new List<T>();
        }

        /// <summary>
        /// 深拷贝数据并加载数据
        /// </summary>
        /// <param name="values"></param>
        public void SetData(List<T> values)
        {
            values ??= new List<T>();
            DataList = JsonConvert.DeserializeObject<List<T>>(JsonConvert.SerializeObject(values));
            DataSelect = DataList?.FirstOrDefault(o => o.IsSelect);
        }

        public ICommand ButCommand { get => new DelegateCommand<string>(But); }
        /// <summary>
        /// 按钮
        /// </summary>
        /// <param name="ty">类型</param>
        public void But(string ty)
        {
            if (DataList == null)
            {
                HandyControl.Controls.MessageBox.Show("请先调用加载数据。");
                return;
            }

            //新增
            if (ty == "add")
            {
                var name = TipInputView.Show("请输入新名称：", (v1) =>
                {
                    if (DataList.Any(o => o.Name == v1?.Trim()))
                        return "名称已存在。";
                    return string.Empty;
                })?.Trim();

                if (name == null)
                    return;

                var px = DataList.Any() ? DataList.Max(o => o.Sort) + 1 : 1;
                var add = new T() { Name = name, IsEnabled = true, Sort = px, IsSelect = true };
                DataList.Add(add);
                DataList = DataList.ToList();
                DataSelect = add;
            }
            //复制
            else if (ty == "cop")
            {
                if (DataSelect == null)
                    return;

                var name = TipInputView.Show($"请输入新名称：（旧名称：{DataSelect.Name}）", (v1) =>
                {
                    if (DataList.Any(o => o.Name == v1?.Trim()))
                        return "名称已存在。";
                    return string.Empty;
                }, DataSelect.Name + "_copy")?.Trim();

                if (name == null)
                    return;

                var px = DataList.Any() ? DataList.Max(o => o.Sort) + 1 : 1;
                var add = JsonConvert.DeserializeObject<T>(JsonConvert.SerializeObject(DataSelect)) ?? new T();
                add.Sort = px;
                add.Name = name;
                DataList.Add(add);
                DataList = DataList.ToList();
                DataSelect = add;
            }
            //删除
            else if (ty == "del")
            {
                if (DataSelect == null)
                    return;

                Growl.Ask("确认删除？", isConfirmed =>
                {
                    if (isConfirmed)
                    {
                        DataList.Remove(DataSelect);
                        DataList = DataList.ToList();
                        DataSelect = DataList.FirstOrDefault();
                        Growl.Success("删除成功。");
                    }
                    return true;
                });
            }
            //更名
            else if (ty == "ren")
            {
                if (DataSelect == null)
                    return;

                var name = TipInputView.Show($"请输入新名称：（旧名称：{DataSelect.Name}）", (v1) =>
                {
                    if (DataList.Where(o => o.Name != DataSelect.Name).Any(o => o.Name == v1?.Trim()))
                        return "名称已存在。";
                    return string.Empty;
                })?.Trim();

                if (name == null)
                    return;

                DataSelect.Name = name;
                DataList = DataList.ToList();
                DataSelect = null;
                DataSelect = DataList.FirstOrDefault(o => o.Name == name);
            }
        }
    }
}
